package petstore.web.servlet.catalog;

import petstore.domain.Category;
import petstore.domain.Log;
import petstore.domain.Product;
import petstore.persistence.LogDaoImpl;
import petstore.persistence.user.UserDAOImpl;
import petstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class CategoryFormServlet extends HttpServlet
{
    private CatalogService catalogService;

    private static final String CATEGORY_FORM = "/WEB-INF/jsp/catalogPage/category.jsp";
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        String categoryId =req.getParameter("categoryId");//获取从request过来的categoryId
        HttpSession session = req.getSession();

        if(session.getAttribute("uid") != null){
            int uid = (int)session.getAttribute("uid");
            UserDAOImpl userDAO = new UserDAOImpl();
       //     System.out.println(uid + " " + categoryId);
            userDAO.UpdataUserdata(uid,categoryId);
        }

        //日志记录存储访问的条目和次数，记录到数据库中
        //Log.getInstance().linkedCategoryUpdate(categoryId);
        //LogDaoImpl logDao = new LogDaoImpl();
        //logDao.UpdateLastTime(Log.getInstance(),Log.getInstance().getLastTime());

        catalogService = new CatalogService();//实例化一个CatalogService对象
        Category category = catalogService.getCategory(categoryId);//利用获取的categoryId，获取category相关信息
        List<Product> productList = catalogService.getProductListBycategoryId(categoryId);//利用获取的categoryId，获取所有Product相关信息

        //向jsp传递

        session.setAttribute("category",category);
        session.setAttribute("productList",productList);
        req.getRequestDispatcher(CATEGORY_FORM).forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}

